#include <stdio.h>
#include <string>
#include "comp.h"

#define MATRIX 24
#define CP_BYTES(m) ((m) * (m) / 8)
using namespace std;

static char CnStore[1024 * 1024];
static char EnStore[100 * 1024];

int LoadStore()
{
	FILE *fp = NULL;
	if ((fp = fopen("ascii24.DZK", "rb")) == NULL)
		return -1;
	int len = 0;
	int n;
	while ((n = fread(&EnStore[len], 1, 4096, fp)) != 0) {
		len += n;
	}
	fclose(fp);

	if ((fp = fopen("HZS16", "rb")) == NULL)
		return -1;
	len = 0;
	while ((n = fread(&CnStore[len], 1, 4096, fp)) != 0) {
		len += n;
	}
	fclose(fp);
	return 0;
}

void draw(const char *str)
{
	long pos;
	char bit[100];

	if ((unsigned char)*str >= 128) {
		pos = 32L * (((unsigned char)(*str) - 161) * 94 + (unsigned char)(*(str + 1)) - 161);
		memcpy(bit, &CnStore[pos], 32);
		for (int i = 0; i < 16; i++) {
			for (int j = 0; j < 2; j++) {
				for (int k = 0; k < 8; k++) {
					if (bit[i * 2 + j] & (0x80U >> k)) {
						printf("o");
					}
					else printf(" ");
				}
			}
			printf("\n");
		}
	}
	else {
		pos = (*str) * 72;
		memcpy(bit, &EnStore[pos], 72);
		for (int i = 0; i < 24; i++) {
			for (int j = 0; j < 3; j++) {
				for (int k = 0; k < 8; k++) {
					if (bit[i * 3 + j] & (0x80U >> k)) {
						printf("o");
					}
					else printf(" ");
				}
			}
			printf("\n");
		}
	}
}

int incise_font(const char *str, COMP_RECT &rect)
{
	long pos;
	char bit[100];
	int first_line = MATRIX - 1, last_line = 0, first_col = MATRIX - 1, last_col = 0;
	pos = (*str) * CP_BYTES(MATRIX);
	memcpy(bit, &EnStore[pos], CP_BYTES(MATRIX));
	for (int i = 0; i < MATRIX; i++) {
		for (int j = 0; j < MATRIX / 8; j++) {
			for (int k = 0; k < 8; k++) {
				if (bit[i * (MATRIX / 8) + j] & (0x80U >> k)) {
					//printf("o");
					if (first_line > i) {
						first_line = i;
					}
					if (last_line < i) {
						last_line = i;
					}
					if (first_col > j * 8 + k) {
						first_col = j * 8 + k;
					}
					if (last_col < j * 8 + k) {
						last_col = j * 8 + k;
					}
				}
				//else printf(" ");
			}
		}
		//printf("\n");
	}

	string data;
	for (int l = first_line; l <= last_line; l++) {
		for (int c = first_col; c <= last_col; c++) {
			if (bit[l * (MATRIX / 8) + (c / 8)] & (0x80 >> (c % 8))) {
				data.insert(data.end(), '0');
			}
			else {
				data.insert(data.end(), '1');
			}
		}
	}
	rect.height = last_line - first_line + 1;
	rect.width = last_col - first_col + 1;
	rect.rect = data;

	return 0;
}
/*
int main(int argc, char **argv)
{
	
	if (LoadStore() < 0) {
		printf("LoadStore failed\n");
		return 0;
	}
	draw("1");
	return 0;
}
*/
